package cn.shop.front.controller.wx;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.shop.base.UserInfoForSession;
import cn.shop.front.config.WeChatConfig;
import cn.shop.front.controller.wx.utils.Constants;
import cn.shop.front.controller.wx.utils.WxUtils;
import cn.shop.front.service.FrontUserService;
import cn.shop.transcation.frontUserModule.FrontUser;
import cn.shop.utils.constant.Constant;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Jzw
 */
@RestController
@Slf4j
@RequestMapping("/api/wx")
public class WxServiceController {

	@Resource
	private WeChatConfig weChatConfig;
	@Resource
	private FrontUserService frontUserService;


	//private static final String APP_ID = "wx91cb0e13076d1c9a";

	//private static final String APP_SECRET = "77d508565712b6416e7110156b0d3a8b";


	/**
	 * -获取openid之后 重定向到前端页面
	 */
	//private static final String FRONT_URL_PREFIX = "http://hr.jinyuntongpay.com/";
	// private static final String FRONT_URL_PREFIX = "http://haojy.nat300.top/";

	/**
	 * -后端code回调地址
	 */
	//private static final String REDIRECT_URI = FRONT_URL_PREFIX + "shop-front/api/wx/bindCallback";

	/**
	 * -后端code回调地址
	 */
	//private static final String REDIRECT_URI_CALLBACK = FRONT_URL_PREFIX + "shop-front/api/wx/callback";


	//private static final String TEMPLATE_ID = "obyqgD0oUKfmfZV4x5-eKmKcyIFWbGDKG5Gpt5cAFvA";

	/**
	 * 用于公众号菜单的绑定账号的url
	 *
	 * @param
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/bind", method = RequestMethod.GET)
	public void bind(HttpServletResponse response) throws IOException {

		String url = Constants.WX_CODE_URL +
				weChatConfig.getAppId() +
				"&redirect_uri=" +
				URLUtil.encode(weChatConfig.getFrontUrlPrefix() + weChatConfig.getRedirectUri()) +
				"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
		System.out.println("url===:" + url);
		response.sendRedirect(url);
	}

	/***
	 * 获取openId 微信回调接口
	 *
	 */
	@RequestMapping(value = "bindCallback", method = RequestMethod.GET)
	public void bindCallback(HttpServletResponse response, @RequestParam("code") String code) throws IOException {
		System.out.println("code==:" + code);
		//已经获取到用户code，就可以根据用户code，获取用户openId
		JSONObject accessTokenInfo = getAccessToken(code);
		String openId = accessTokenInfo.getStr("openid");
		String accessToken = accessTokenInfo.getStr("access_token");
		System.out.println("openId====" + openId);
		if (StrUtil.isNotEmpty(openId)) {
			long id = IdWorker.getId();
			SaSession session = SaSessionCustomUtil.getSessionById(String.valueOf(id));
			session.set("openId", openId);
			session.set("accessToken", accessToken);
			response.sendRedirect(weChatConfig.getFrontUrlPrefix() + "wx/#/login?token=" + id);
		}
	}

	/**
	 * 用于公众号菜单的个人中心的url
	 *
	 * @param
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/grant", method = RequestMethod.GET)
	public void grant(HttpServletResponse response) throws IOException {
		System.out.println("===========1==========");

		String url = Constants.WX_CODE_URL +
				weChatConfig.getAppId() +
				"&redirect_uri=" +
				URLUtil.encode(weChatConfig.getFrontUrlPrefix() + weChatConfig.getRedirectUriCallBack()) +
				"&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect";
		System.out.println("url===:" + url);
		response.sendRedirect(url);
	}

	/***
	 * 获取openId 微信回调接口
	 *
	 */
	@RequestMapping(value = "callback", method = RequestMethod.GET)
	public void callback(HttpServletResponse response, @RequestParam("code") String code) throws IOException {
		System.out.println("===========2==========");
		System.out.println("code==:" + code);
		//已经获取到用户code，就可以根据用户code，获取用户openId
		String openId = getOpenId(code);
		System.out.println("openId====" + openId);
		FrontUser frontUser = frontUserService.lambdaQuery()
				.eq(FrontUser::getOpenId, openId)
				.one();
		String token = null;
		if (frontUser != null) {
			Long frontUserId = frontUser.getId();

			StpUtil.login(frontUserId);
			String account = frontUser.getAccount();
			String name = frontUser.getName();
			StpUtil.getSession().set(Constant.USER, new UserInfoForSession(frontUserId, account, name));
			token = StpUtil.getTokenValue();
		}
		response.sendRedirect(weChatConfig.getFrontUrlPrefix() + "wx/#/?token=" + token);
	}

	private JSONObject getAccessToken(String code) {
		String params = "?appid=" + weChatConfig.getAppId() + "&secret=" + weChatConfig.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
		String url = Constants.WX_ACCESS_TOKEN_URL;
		String res = HttpUtil.get(url + params);
		log.info("通过请求获取 微信access_token : {}", res);
		return JSONUtil.parseObj(res);
	}

	private String getOpenId(String code) {
		JSONObject accessToken = getAccessToken(code);
		return accessToken.getStr("openid");
	}


	/***
	 * 发送微信模板消息
	 * @params tmplateId:微信模板ID,appId,secret,openId
	 */
	@CrossOrigin
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public void test(HttpServletRequest request, HttpServletResponse response) {
		//我的openId: oaCNj6FuO1Jr_a2u9Q79i2dif8-0
		String openId = "oaCNj6FuO1Jr_a2u9Q79i2dif8-0";
		try {
			String result = WxUtils.noticeTemplate(weChatConfig.getTemplateId(), weChatConfig.getAppId(), weChatConfig.getAppSecret(), openId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
